package com.xjl.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xjl.demo.WebInfo;
import com.xjl.service.WebinfoService;
import com.xjl.service.impl.WebinfoServiceImpl;

@WebServlet("/updatewebinfo.do")
@MultipartConfig 
public class UpdateWebInfoServlet extends HttpServlet {
	WebinfoService wb = new WebinfoServiceImpl();
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;utf-8");
		WebInfo info = new WebInfo();
		info.setId(1);
		info.setTitle(req.getParameter("title"));
		//文件上传，
			Part part = req.getPart("logo");
	        String disposition = part.getHeader("Content-Disposition");
	        String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
	          //随机的生存一个32的字符串+文件名
	     //   String filename = UUID.randomUUID()+suffix;
	        String filename = "logo"+suffix;
	       
	          //获取上传的文件名
	        InputStream is = part.getInputStream();
	        //动态获取服务器的路径
	        //将图片保存到E:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\pcshop\\upload中。
	        //服务器存放图片，数据库存放图片名
	        String serverpath = req.getServletContext().getRealPath("upload");
	        FileOutputStream fos = new FileOutputStream(serverpath+"/"+filename);
	        byte[] bty = new byte[1024];
	        int length =0;
	        while((length=is.read(bty))!=-1){
	            fos.write(bty,0,length);
	        }
	        fos.close();
	        is.close();
		info.setLogo(filename);
		info.setDns(req.getParameter("dns"));
		info.setDes(req.getParameter("des"));
		info.setName(req.getParameter("name"));
		info.setQq(req.getParameter("qq"));
		info.setPhone(req.getParameter("phone"));
		info.setEmail(req.getParameter("email"));
		info.setAddress(req.getParameter("address"));
		info.setBinfo(req.getParameter("binfo"));
		int index = wb.UpdateWebInfoService(info);
		//获取session
		HttpSession session = req.getSession();
		if(index==1){
			session.setAttribute("flag3", "更新成功,刷新页面生效！");
		}else{
			session.setAttribute("flag3", "网络异常，请稍后在试！");
		}
		
		resp.sendRedirect("/pcshop/showweb.do");
		return;
	}

}
